import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { message } from "antd";

// 创建axios实例
const request: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || "/api",
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 从localStorage获取token
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    // 可以在这里添加其他全局配置
    return config;
  },
  (error) => {
    console.error("请求错误:", error);
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    // 直接返回数据部分
    const { data } = response;

    // 根据后端返回的数据结构进行调整
    // 假设后端返回格式: { code: 200, data: {...}, message: 'success' }
    if (data.code === 200 || data.code === 0) {
      return data.data || data;
    }

    // 处理业务错误
    if (data.message) {
      message.error(data.message);
    }

    return Promise.reject(new Error(data.message || "请求失败"));
  },
  (error) => {
    console.error("响应错误:", error);

    // 处理HTTP错误
    if (error.response) {
      const { status, data } = error.response;

      switch (status) {
        case 400:
          message.error(data?.message || "请求参数错误");
          break;
        case 401:
          message.error("登录已过期，请重新登录");
          // 清除token
          localStorage.removeItem("token");
          localStorage.removeItem("userInfo");
          // 跳转到登录页
          window.location.href = "/login";
          break;
        case 403:
          message.error("没有权限访问");
          break;
        case 404:
          message.error("请求的资源不存在");
          break;
        case 500:
          message.error("服务器错误，请稍后重试");
          break;
        case 502:
          message.error("网关错误");
          break;
        case 503:
          message.error("服务不可用");
          break;
        default:
          message.error(data?.message || "网络错误，请稍后重试");
      }
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      message.error("网络错误，请检查您的网络连接");
    } else {
      // 其他错误
      message.error(error.message || "请求失败");
    }

    return Promise.reject(error);
  }
);

// 封装GET请求
export const get = <T = any>(
  url: string,
  params?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  return request.get(url, { params, ...config });
};

// 封装POST请求
export const post = <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  return request.post(url, data, config);
};

// 封装PUT请求
export const put = <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  return request.put(url, data, config);
};

// 封装DELETE请求
export const del = <T = any>(
  url: string,
  params?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  return request.delete(url, { params, ...config });
};

// 封装PATCH请求
export const patch = <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  return request.patch(url, data, config);
};

// 上传文件
export const upload = <T = any>(
  url: string,
  formData: FormData,
  onProgress?: (progressEvent: any) => void
): Promise<T> => {
  return request.post(url, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
    onUploadProgress: onProgress,
  });
};

export default request;
